//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.SilverlightChat
{
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using Microsoft.Samples.ServiceBus.Messaging;
    using Microsoft.Samples.ServiceBus.SilverlightChat.Models.ViewModels;

    public partial class ChatWindow : UserControl
    {
        public ChatWindow()
        {
            // Required to initialize variables
            InitializeComponent();
        }

        public ChatWindowViewModel ViewModel
        {
            get { return this.DataContext as ChatWindowViewModel; }
        }

        /// <summary>
        /// If the specified sender is the current topic, appends the message to 
        /// the end of the chat text box.
        /// </summary>
        internal void AppendMessage(ChatTopicViewModel sender, BrokeredMessage message)
        {
            if (this.ViewModel.CurrentTopic == sender && message != null)
            {
                // Get a view model of the message that was received (including the
                // sender name and body
                var messageViewModel = ChatMessageViewModel.Create(message);

                // format the message view model as a Rich Text block
                var richTextBlock = messageViewModel.CreateRichTextBlock();

                // append the new block to end end of the rich text box
                this.currentChatTextBox.Blocks.Add(richTextBlock);
            }
        }

        /// <summary>
        /// Called when the 'Enter'/'Return' key is pressed within the Text Box
        /// </summary>
        private void OnChatMessageBoxTextInput(object sender, TextCompositionEventArgs e)
        {
            // Force the ViewModel to be updated to the current value of the TextBox's text
            var bindingExpression = ((TextBox)sender).GetBindingExpression(TextBox.TextProperty);
            bindingExpression.UpdateSource();

            // If a topic is currently selected, execute the SendMessageCommand to
            // send the message to the current topic
            if (this.ViewModel.SendMessageCommand.CanExecute(this.ViewModel.CurrentMessage))
            {
                this.ViewModel.SendMessageCommand.Execute(this.ViewModel.CurrentMessage);
            }
        }

        /// <summary>
        /// When the currently selected topic changes, update the IsCurrentTopic
        /// property on any selected and deselected topics. Also update the UI so 
        /// that when no topic is selected, the chat area is hidden.
        /// </summary>
        private void OnSelectedTopicChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (var topic in e.RemovedItems.OfType<ChatTopicViewModel>())
            {
                topic.IsCurrentTopic = false;
            }

            this.currentChatTextBox.Blocks.Clear();

            foreach (var topic in e.AddedItems.OfType<ChatTopicViewModel>())
            {
                topic.IsCurrentTopic = true;
            }

            var state = this.ViewModel.Topics.Any(t => t.IsCurrentTopic) ? "TopicSelected" : "NothingSelected";
            VisualStateManager.GoToState(this, state, false);
        }
    }
}
